#!/usr/bin/env bash

# 安装必要的软件包
echo "正在安装 yum-utils device-mapper-persistent-data lvm2..."
sudo yum install -y yum-utils device-mapper-persistent-data lvm2 || {
    echo "错误：无法安装必要的软件包"
    exit 1
}

echo "必要的软件包安装成功"

# 添加 Docker YUM 源
echo "正在添加 Docker YUM 源..."
sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo || {
    echo "错误：无法添加 Docker YUM 源"
    exit 1
}

echo "Docker YUM 源添加成功"

# 安装 containerd
echo "正在安装 containerd..."
sudo yum -y install containerd || {
    echo "错误：无法安装 containerd"
    exit 1
}

echo "containerd 安装成功"

# 生成 containerd 默认配置文件
echo "正在生成 containerd 默认配置文件..."
sudo mkdir -p /etc/containerd
containerd config default | sudo tee /etc/containerd/config.toml >/dev/null || {
    echo "错误：无法生成配置文件"
    exit 1
}

echo "配置文件生成成功"

# 修改 cgroup 驱动为 systemd
echo "正在修改 cgroup 驱动为 systemd..."
sudo sed -i 's/SystemdCgroup = false/SystemdCgroup = true/g' /etc/containerd/config.toml || {
    echo "错误：无法修改 cgroup 驱动"
    exit 1
}

# 修改 sandbox 拉取镜像地址
echo "正在修改 sandbox 拉取镜像地址..."
sudo sed -i 's/sandbox_image = .*/sandbox_image = "registry.aliyuncs.com\/google_containers\/pause:3.9"/g' /etc/containerd/config.toml || {
    echo "错误：无法修改 sandbox 镜像地址"
    exit 1
}

# 验证配置
echo "验证配置结果："
echo "1. cgroup 驱动是否为 systemd："
grep "SystemdCgroup = true" /etc/containerd/config.toml || {
    echo "错误：cgroup 驱动未正确配置"
    exit 1
}

echo "2. sandbox 镜像地址是否正确："
grep "sandbox_image" /etc/containerd/config.toml || {
    echo "错误：sandbox 镜像地址未正确配置"
    exit 1
}

# 启动并启用 containerd 服务
echo "正在启动并启用 containerd 服务..."
sudo systemctl daemon-reload
sudo systemctl start containerd || {
    echo "错误：无法启动 containerd 服务"
    exit 1
}

sudo systemctl enable containerd || {
    echo "错误：无法启用 containerd 服务"
    exit 1
}

echo "containerd 服务已成功启动并启用"
echo "所有配置验证通过，脚本执行成功"
